<?php
declare (strict_types=1);

namespace app\sysuser\controller\subject;

use app\common\controller\SysBackend;
use app\common\enums\SubjectKnowledgeStatusEnum;
use app\common\model\banxi\subject\SubjectKnowledge;
use app\common\model\banxi\subject\SubjectKnowledge as SubjectKnowledgeModel;
use app\common\model\banxi\subject\SubjectTeach as SubjectTeachModel;
use app\common\model\banxi\subject\SubjectTeachChapter;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class Teach extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SubjectTeachModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);

        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->where($where)
            ->with([
                'courseDictInfo' => function ($query) {
                    $query->field('id,name');
                }, 'gradeInfo' => function ($query) {
                    $query->field('id,name');
                }, 'subject' => function ($query) {
                    $query->field('id,name');
                }, 'knowledge' => function ($query) {
                    $query->field('id,pid,name');
                }])
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ])->each(function ($item) {
                if (!empty($item['knowledge'])) {
                    if (!empty($item['knowledge']['pid'])) {
                        $pid = $item['knowledge']['pid'];
                        $pidKnowledge = SubjectKnowledgeModel::where(['id' => $pid, 'status' => SubjectKnowledgeStatusEnum::E1])->field('id,name')->find();
                        unset($item['knowledge']['pid']);
                        $pidKnowledge['children'] = $item['knowledge'];
                        $item['knowledge'] = $pidKnowledge;
                    } else {
                        $item['knowledge']['children'] = null;
                        unset($item['knowledge']['pid']);
                    }
                }
                $item['chapterNum'] = SubjectTeachChapter::where([
                    'subjectTeachId' => $item['id']
                ])->count();
            });
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 分页Select查询
     * @return void
     * @throws DbException
     */
    public function listSelectPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->where($where)
            ->field('id,name')
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ]);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->where($where)->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $this->ok('操作成功', $info);
    }

    /**
     * 新增或修改
     * @return void
     */
    public function saveOrUpdate()
    {
        $param = $this->request->param([
            'id' => null,
            'showImage' => '',
            'name' => '',
            'sortNum' => 0,
            'subjectId' => 0,
            'subjectCourseDictId' => 0,
            'subjectGradeId' => 0,
            'status' => 0,
            'subjectKnowledgeId' => 0
        ]);
        try {
            $validate = Validate::rule([
                'showImage' => ValidateRule::isRequire(null, '请上传封面图片'),
                'name' => ValidateRule::isRequire(null, '请输入班级名称'),
                'sortNum' => ValidateRule::isNumber(null, '请输入正确的排序数字'),
                'subjectId' => ValidateRule::gt(0, '请选择科目'),
                'subjectCourseDictId' => ValidateRule::gt(0, '请选择教材'),
                'subjectGradeId' => ValidateRule::gt(0, '请选择年级'),
                'status' => ValidateRule::in([1, 2], '请选择正确的状态'),
                'subjectKnowledgeId' => function ($value) {
                    $isExists = SubjectKnowledge::where(['id' => $value, 'status' => SubjectKnowledgeStatusEnum::E1])->count() > 0;
                    if ($isExists) {
                        return true;
                    }
                    return '知识点不存在';
                }
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->saveOrUpdate($param);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }


    public function del()
    {
        $param = $this->request->param(['ids' => []]);
        try {
            $validate = Validate::rule([
                'ids' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            SubjectTeachModel::destroy(function ($query) use ($param) {
                $query->whereIn('id', $param['ids']);
            });
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }
}
